package com.anuyun.ms.ums.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.anuyun.ms.base.common.BusinessException;
import com.anuyun.ms.base.constant.TimeConstant;
import com.anuyun.ms.base.util.DateUtil;
import com.anuyun.ms.base.util.JwtUtil;
import com.anuyun.ms.ums.config.Constant;
import com.anuyun.ms.ums.dao.UserDao;
import com.anuyun.ms.ums.entity.User;
import com.anuyun.ms.ums.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


@Service
public class UserServiceImpl implements UserService {

	@Autowired
	UserDao userDao;
	
	
	

	@Override
	public User insert(User user) {
		if(userDao.getByUserName(user.getUserName()) != null) {
			throw new BusinessException("用户名已存在");
		}
		
		userDao.insert(user);
		return userDao.getByUserName(user.getUserName());
	}
	
	
	
	
	@Override
	public Page<User> list(Map<String,String> queryVO) {
		QueryWrapper<User> wrapper = new QueryWrapper<>();
		wrapper.eq("email", queryVO.get("email"));
		wrapper.like("name",queryVO.get("name"));
		wrapper.orderByAsc(false, "name");
		
		Page<User> userPage = new Page<>(1, 10);
		userPage= userDao.selectPage(userPage, wrapper);
		return userPage;
	}




	@Override
	public User get(String id) {
		if (StringUtils.isBlank(id)) {
			throw new BusinessException(1, "id不能为空");
		}

		User user = userDao.selectById(id);
		if (ObjectUtils.isEmpty(user)) {
			throw new BusinessException(1, "未找到该用户");
		}
		
		
		
		//隐藏密码
		user.setPassword("");
		

		return user;
	}

	@Override
	public Map<String,Object> login(User user) {

		String userName = user.getUserName();
		if (StringUtils.isBlank(user.getUserName())) {
			throw new BusinessException(1, "用户名不能为空");
		}

		String password = user.getPassword();
		if (StringUtils.isBlank(password)) {
			throw new BusinessException(1, "密码不能为空");
		}

		// 查询用户
		user = userDao.getByUserName(userName);
		if (ObjectUtils.isEmpty(user)) {
			throw new BusinessException(1, "用户名不存在");
		}

		String lastErrorTime = user.getLastErrorTime();

		boolean isLockTimeout = false;// 距离上次登录失败时间，是否已过时，30分钟过时

		long needMinute = Constant.LOGIN_LOCK_TIME;// 需要多久才能再次登录，默认30分钟

		if (StringUtils.isBlank(lastErrorTime)) {// 第一次登录
			isLockTimeout = true;
		} else {
			LocalDateTime dateTime = DateUtil.toLocalDateTime(lastErrorTime, TimeConstant.TIME_FORMAT);
			isLockTimeout = DateUtil.isTimeOut(dateTime, Constant.LOGIN_LOCK_TIME * 60);
			needMinute = Constant.LOGIN_LOCK_TIME - DateUtil.differMinutes(dateTime);
		}

		// 校验用户是否锁定 锁定状态并且锁定时间未过时
		if (user.getLocked() == 1 && !isLockTimeout) {
			if (user.getErrorTimes() != 0) {
				user.setErrorTimes(0);
				userDao.updateLoginInfo(user);
			}
			throw new BusinessException(1, "用户已被锁定，请" + needMinute + "分钟后重试");
		}

		// 校验密码
		if (userDao.login(userName, password) < 1) { // 登录失败
			// 记录登录时间，登录次数
			String nowTime = DateUtil.toString(LocalDateTime.now(), TimeConstant.TIME_FORMAT);
			user.setLastErrorTime(nowTime);
			int errotTimes = user.getErrorTimes() + 1;
			user.setErrorTimes(errotTimes);
			String errorMsg = "登录失败，密码错误";
			if (Constant.LOGIN_ERROR_TIMES <= errotTimes) {
				user.setLocked(1);
				user.setErrorTimes(0);
				userDao.updateLoginInfo(user);
				errorMsg = "连续登录失败次数过多，用户已被锁定，锁定时间" + Constant.LOGIN_LOCK_TIME + "分钟";
			}
			userDao.updateLoginInfo(user);
			throw new BusinessException(1, errorMsg);
		} else {// 登录成功
			user.setErrorTimes(0);
			user.setLocked(0);
			userDao.updateLoginInfo(user);
			
		}
		String token = JwtUtil.sign(user);
		user.setPassword("");
		Map<String,Object> reslut = new HashMap<>();
		reslut.put("user", user);
		reslut.put("token", token);

		return reslut;
	}

}
